<?php

namespace app\components;

use Yii;
use Exception;
use yii\helpers\Html;

/**
 * 公共静态方法类
 */
class Common
{
    /**
     * 显示信息
     * @param type $msg
     * @param type $flag
     * @param type $redirect
     */
    public static function showMsg($msg, $flag, $redirect) {

        Yii::$app->session->setFlash("flag", $flag);
        Yii::$app->session->setFlash("msg", $msg);

        echo "<script>window.location.href='" . $redirect . "'</script>";
        exit();
    }

    public static function renderCsrf()
    {
        return Html::hiddenInput('_csrf', Yii::$app->request->getCsrfToken());
    }

    public static function setShowMsg($flag ,$msg){
        Yii::$app->session->setFlash('msg', $msg);
        Yii::$app->session->setFlash('flag', $flag);
    }

    public static function showViewMsg() {
        if (Yii::$app->session->hasFlash('msg')) {
            $class = Yii::$app->session->getFlash('flag') == true ? 'mint' : 'danger';
            $icon = Yii::$app->session->getFlash('flag') == true ? 'check' : 'warning';
            $str = "<div class='alert alert-" . $class . " fade in'>";
            $str.='<button class="close" data-dismiss="alert"> × </button>';
            $str.='<i class="fa-fw fa fa-' . $icon . '"></i>';
            $str . '<strong>' . $class . '</strong>';
            $str.= Yii::$app->session->getFlash('msg');
            $str.='</div>';
            echo $str;
        }
    }

    public static function printLog($msg) {
        echo date("Y/m/d H:i:s") . ' ' . $msg . "\n\r";
    }

    public static function request($url, $method = 'POST' ,$host,$lang ,$agent ,$body = null , $timeout = 30)
    {
        $ch = curl_init();
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HTTPHEADER => array(
                "Host"=> $host,
                "Accept-Language"=> $lang,
            ),
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => $agent,
        );
        if($method == 'POST'){
            $options[CURLOPT_POST] = TRUE;
        }else{
            $options[CURLOPT_HTTPGET] = TRUE;
        }

        if(!is_null($body)){
            $options[CURLOPT_POSTFIELDS] = http_build_query($body);
        }

        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        if ($errno = curl_errno($ch))
            throw new Exception("Send request error:" . curl_error($ch), 1009, 500);
        return $result;
    }
}